package com.ruoyi.web.controller.student;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.domain.ScreenshotDTO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

@RestController
@RequestMapping("/loading/saveScreenshot")
public class ScreenshotController {


    @PostMapping
    public ResponseEntity<?> saveScreenshot(@RequestBody ScreenshotDTO screenshotDTO) {
        String base64Image = screenshotDTO.getImageData().split(",")[1];
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        Path path = Paths.get(RuoYiConfig.getProfile()+"/down");

        try  {
            String filePath = saveImage(
                    screenshotDTO.getImageData()
            );
            return ResponseEntity.ok("截图保存成功");
        } catch (IOException e) {
            System.err.println("Error saving image: " + e.getMessage());
        }
        return null;
    }

    public String saveImage(String base64Data) throws IOException {
        String[] parts = base64Data.split(",");
        byte[] imageBytes = Base64.getDecoder().decode(parts[1]);

        String fileName = "screenshot_" + System.currentTimeMillis() + ".png";
        Path path = Paths.get(RuoYiConfig.getProfile()+"/down/", fileName);

        Files.createDirectories(path.getParent());
        Files.write(path, imageBytes);

        return path.toString();
    }
}
